package com.example.demo.controllerApi;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import com.example.demo.entity.UserInfoTest;
import com.example.demo.service.UserInfoTestService;
import com.example.demo.util.AjaxJson;
import com.example.demo.util.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Optional;

/**
 * @Author: Pinp
 * @Date: 2021/7/21 1:29
 */

@Slf4j
@RestController
@RequestMapping("/api")
public class LoginApi {

    @Autowired
    private UserInfoTestService us;

    @PostMapping("doLogin")
    public AjaxJson doLogin(HttpSession session, @RequestParam String name, @RequestParam String password){
        log.info(name + " " + password);
        AjaxJson aj = null;
        Optional<UserInfoTest> ui = us.getUser(name, password);
        log.info(ui.toString());
        if (ui.isPresent()) {
            int id = ui.get().getId();
            String username = ui.get().getName();
            StpUtil.login(id);
            SaSession saSession = StpUtil.getSession(true);
            saSession.set("userId", id);
            saSession.set("name", username);
            saSession.set("loginName", name);
            saSession.set("roleId", 1);
            session.setAttribute("userId", id);
            session.setAttribute("name", username);
            session.setAttribute("loginName", name);
            session.setAttribute("roleId", 1);
        }else {
            return AjaxJson.getError("Username or password is wrong!");
        }
        return AjaxJson.getSuccess();
    }

    @GetMapping("doLogout")
    public AjaxJson doLogout(HttpSession session){
        StpUtil.logout();
        session.invalidate();
        return AjaxJson.getByBoolean(true);
    }

    @RequestMapping("isLogin")
    public AjaxJson isLogin() throws Exception{
        boolean flag = StpUtil.isLogin();
        log.debug(String.valueOf(flag));
        JSONObject jData = new JSONObject();
        jData.set("flag",flag);
        if (!flag){
            throw new CustomException("xxx");
        }
//        jData.set("roles", SaSessionCustomUtil.getSessionById("Roles").get("Role_List"));
//        jData.set("roleId",StpUtil.getSession().get("roleId"));
        return AjaxJson.getSuccessData(jData);
    }

    @RequestMapping("getTokenInfo")
    public AjaxJson getTokenInfo(){
        SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
        return AjaxJson.getSuccessData(saTokenInfo);
    }

}
